import { homeRoutes, asyncRoutes } from '../../router/router'
/**
 *根据角色过滤路由
 * @param roles
 * @param route
 * @returns {boolean|*}
 */
function hasPermission(roles , route) {
    if(route.meta && route.meta.role){
        return route.some(role => route.meta.roles.includes(role))
    }else{
        return true
    }
}
export function filterAsyncRoutes1(routes, roles) {
    const res = []

    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            res.push(tmp)
        }
    })

    return res
}
/**
 * 循环过滤该角色能访问的路由
 * @param routes
 * @param roles
 * @returns {[]}
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes1(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}
const state = {
    routes:[],
    addRoutes:[],
    isGetRoutes:false
}
const mutations = {
    setRouters(state,routes){
        state.routes = homeRoutes.concat(routes);
    },
    isGetRoutesChange(state,isBoole){
        state.isGetRoutes = isBoole
    }
}
const actions = {
    generateRoutes({ commit } , roles){
        return new Promise(resolve => {
        let accessedRoutes
        if(roles.includes('admin')){
            accessedRoutes = asyncRoutes || []
        }else {
            accessedRoutes = filterAsyncRoutes(asyncRoutes,roles)
        }

            commit('setRouters',accessedRoutes);
            resolve(accessedRoutes)
        })
    },
    setIsGetRoutes({ commit } , isBoole){
        commit('isGetRoutesChange',isBoole)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
